package org.southyin.securitysamples.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.southyin.securitysamples.commons.CommonsResp;
import org.southyin.securitysamples.model.User;
import org.southyin.securitysamples.service.CmsLogService;
import org.southyin.securitysamples.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfiguration.class);
    @Autowired
    MyFilterDatasource filterDatasource;
    @Autowired
    MyAccessDecision accessDecision;

    @Autowired
    CmsLogService service;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/login",
                "/swagger**/**",
                "/v3/**",
                "/webjars/**",
                "/doc.html");
    }

    @Autowired
    LoginService loginService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(loginService);
    }

    private CorsConfigurationSource CorsConfigurationSource() {
        CorsConfigurationSource source =   new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");    //同源配置，*表示任何请求都视为同源，若需指定ip和端口可以改为如“localhost：8080”，多个以“，”分隔；
        corsConfiguration.addAllowedHeader("*");//header，允许哪些header，本案中使用的是token，此处可将*替换为token；
        corsConfiguration.addAllowedMethod("*");    //允许的请求方法，PSOT、GET等
        ((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**",corsConfiguration); //配置允许跨域访问的url
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(CorsConfigurationSource())
                .and()
                .authorizeRequests()
//                // /admin/** 这种接口 需要 admin 角色
//                .antMatchers("/admin/**").hasRole("admin")
//                .antMatchers("/user/**").hasAnyRole("admin,user")
//                // 其他接口 登录即可访问
//                .anyRequest().authenticated()
                // 处理器
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(filterDatasource);
                        o.setAccessDecisionManager(accessDecision);
                        return o;
                    }
                })
                .and()
                // 登录相关接口放行
                .formLogin()
                // 没有登录的提示接口
                .loginPage("/login")
                // 登录接口
                .loginProcessingUrl("/doLogin")
                // 用户名参数
                .usernameParameter("username")
                // 用户密码参数
                .passwordParameter("password")
                // 登录成功的 handler
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setCharacterEncoding("utf-8");
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        // 登录者信息
                        User principal = ((User) authentication.getPrincipal());
                        principal.setPassword(null);
                        CommonsResp success = CommonsResp.succeess(200, "登录成功",principal);
                        String remoteAddr = req.getRemoteAddr();
                        service.saveLog(remoteAddr,"登录");
                        writer.println(new ObjectMapper().writeValueAsString(success));
                    }
                })
                // 登录失败的 handler
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setCharacterEncoding("utf-8");
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        CommonsResp failed = null;
                        if (e instanceof BadCredentialsException) {
                            failed = CommonsResp.failed(500, "用户名或密码错误");
                        } else if (e instanceof LockedException) {
                            failed = CommonsResp.failed(500, "用户名被锁定，请联系管理员");
                        } else if (e instanceof DisabledException) {
                            failed = CommonsResp.failed(500, "用户名被禁用，请联系管理员");
                        } else if (e instanceof CredentialsExpiredException) {
                            failed = CommonsResp.failed(500, "用户密码过期，请联系管理员");
                        } else if (e instanceof AccountExpiredException) {
                            failed = CommonsResp.failed(500, "账户过期，请联系管理员");
                        } else{
                            failed = CommonsResp.failed(500, "未知原因，请联系管理员");
                        }
                        writer.println(new ObjectMapper().writeValueAsString(failed));
                    }
                })
                // 放行
                .permitAll()
                .and()
                // 用户退出相关
                .logout()
                // 用户退出接口
                .logoutUrl("/logout")
                // 用户退出成功的 handler
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setCharacterEncoding("utf-8");
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        CommonsResp success = CommonsResp.succeess(200, "退出成功");
                        if (authentication != null) {
                            String remoteAddr = req.getRemoteAddr();
                            service.saveLog(remoteAddr,"退出");
                        }
                        writer.println(new ObjectMapper().writeValueAsString(success));
                    }
                })
                // 放行
                .permitAll()
                // 禁止跨站请求伪造
                .and().csrf().disable();
    }
}
